package com.kwlt.smc.service.impl;

import java.io.File;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kwlt.smc.dao.SmsSendDetailDao;
import com.kwlt.smc.dao.UserChannelDao;
import com.kwlt.smc.entity.Channel;
import com.kwlt.smc.entity.InterRespInfo;
import com.kwlt.smc.entity.SmsInfo;
import com.kwlt.smc.entity.SmsSendDetail;
import com.kwlt.smc.entity.User;
import com.kwlt.smc.service.ISendSms;
import com.kwlt.smc.service.JedisService;
import com.kwlt.smc.service.KeywordService;
import com.kwlt.smc.util.ConUtils;
import com.kwlt.smc.util.Constants;
import com.kwlt.smc.util.ModelConvJson;
import com.kwlt.smc.web.SendSmsController;


@Component(value="sendMmsToFile")
public class SendSmsToFile implements ISendSms {
	public static Logger logger =  LoggerFactory.getLogger(SendSmsController.class);
	@Autowired
	private SmsSendDetailDao smsSendDetailDao;
	@Autowired
	private UserChannelDao userChannelDao;
	@Autowired
	private KeywordService keywordService;
	@Override
	public void sendSmsToStorage(SmsInfo smsInfo,
			InterRespInfo interRespInfo,String localMsgId) {
		JedisService<SmsSendDetail> jedisService = new JedisService<SmsSendDetail>(Constants.REDIS_IP, Constants.REDIS_PASSWORD);
		String dest = smsInfo.getDest();
		Set<String> mobileChannelSet = new HashSet<String>();//移动发送通道
		Set<String> unicomChannelSet = new HashSet<String>();//联通发送通道
		Set<String> telecomChannelSet = new HashSet<String>();//电信发送通道
		List<SmsSendDetail> list = new ArrayList<SmsSendDetail>();
		List userChannel = userChannelDao.getUserChannel(smsInfo.getUser());
		List<Channel> channelList = getChannelList(userChannel);
		List<Channel> mobileList = new ArrayList<Channel>();//移动通道列表
		List<Channel> unicomList = new ArrayList<Channel>();//联通通道列表
		List<Channel> telecomList = new ArrayList<Channel>();//电信通道列表
		for(Channel channel:channelList){
			if(keywordService.validationKeyword(smsInfo, "2", Constants.MOBILE, null)){
				if(Constants.MOBILE.equals(channel.getOperators())){
					if(keywordService.validationKeyword(smsInfo, "3", null, channel.getNumbers())){
						mobileList.add(channel);
					}
					
				}
			}
			if(keywordService.validationKeyword(smsInfo, "2", Constants.TELECOM, null)){
				if(Constants.TELECOM.equals(channel.getOperators())){
					if(keywordService.validationKeyword(smsInfo, "3", null, channel.getNumbers())){
						telecomList.add(channel);
					}
				}
			}
			if(keywordService.validationKeyword(smsInfo, "2", Constants.UNICOM, null)){
				if(Constants.UNICOM.equals(channel.getOperators())){
					if(keywordService.validationKeyword(smsInfo, "3", null, channel.getNumbers())){
						unicomList.add(channel);
					}
				}
			}
		}
		for(String phone:dest.split(",")){
			if(ConUtils.isMobileNo(phone)){
				sendSms(phone, mobileList, smsInfo, localMsgId, list, mobileChannelSet,Constants.MOBILE,jedisService);
			}
			if(ConUtils.isTelecomNo(phone)){
				sendSms(phone, telecomList, smsInfo, localMsgId, list, telecomChannelSet,Constants.TELECOM,jedisService);
			}
			if(ConUtils.isUnicomNo(phone)){
				sendSms(phone, unicomList, smsInfo, localMsgId, list, unicomChannelSet,Constants.UNICOM,jedisService);
			}
		}
		String date = "201"+localMsgId.substring(4,7);
		smsSendDetailDao.save(list,date);
		smsInfo.setMobileChannelSet(mobileChannelSet);
		smsInfo.setUnicomChannelSet(unicomChannelSet);
		smsInfo.setTelecomChannelSet(telecomChannelSet);
		interRespInfo.setMsgId(smsInfo.getMsgid()==null?localMsgId:smsInfo.getMsgid());	
		jedisService.closeJedis();
	}
	/**
	 * 发送
	 * @param phone 手机号
	 * @param channelList 移动通道列表
	 * @param smsInfo 提交信息
	 * @param localMsgId 本地消息ID
	 * @param list 发送详情
	 * @param channelSet 发送通道
	 */
	private void sendSms(String phone,List<Channel> channelList,SmsInfo smsInfo,
			String localMsgId,List<SmsSendDetail> list,Set<String> channelSet,String opreators,JedisService<SmsSendDetail> jedisService){
		SmsSendDetail detail = new SmsSendDetail();
		if(channelList.size()>0){
			int interval = setChannelInterval(channelList);//设置权重
			int rom = (int)(Math.random()*interval);
			int index = 0;
			for(Channel channel:channelList){
				if(channel!=null){
					Long weight = channel.getWeight();
					if((rom>=index) && rom<(index+weight))
					{
						if(opreators.equals(Constants.MOBILE)){
							sendMobileResultToFile(channel,smsInfo,phone,localMsgId);
						}else if(opreators.equals(Constants.TELECOM)){
							sendTelecomResultToFile(channel,smsInfo,phone,localMsgId);
						}else{
							sendUnicomResultToFile(channel,smsInfo,phone,localMsgId);
						}
						channelSet.add(channel.getNumbers());
						detail = getSmsSendDetail(channel, smsInfo, phone, localMsgId,opreators);
						break;
					}
					index +=weight.intValue();
				}
			}
		}else{
			detail = getSmsSendDetail(null, smsInfo, phone, localMsgId,opreators);
		}
		//判断是否个性化用户，保存redis信息
		if("Y".equals(smsInfo.getIsRedis())){
			ModelConvJson<SmsSendDetail> mcj = new ModelConvJson<SmsSendDetail>();
			String json = mcj.getJson(detail);
			jedisService.saveString(detail.getLocalMsgId()+detail.getPhoneNum(), json);
		}
		int len = smsInfo.getResult().length();
		if(len>70){
			for(int i=0;i<len/67+1;i++){
				list.add(detail);
			}
		}else{
			list.add(detail);
		}
	}
	
	/**
	 * 设置各个通道的权重区间
	 * @param channelList
	 */
	private int setChannelInterval(List<Channel> channelList){
		Long weightSum = 0l;//权重总值
		for(Channel channel:channelList){
			if(channel!=null && channel.getWeight()!=null){
				weightSum = weightSum + channel.getWeight();
			}
		}
		return weightSum.intValue();
	}
	
	
	private SmsSendDetail getSmsSendDetail(Channel channel,SmsInfo smsInfo,String phone,
			String localMsgId,String operators){
		SmsSendDetail detail = new SmsSendDetail();
		detail.setChannel(channel==null?"-101":channel.getNumbers());
		detail.setPhoneNum(phone);
		detail.setUser(smsInfo.getUser());
		detail.setIntSubmitDate(new Date());
		detail.setIntMsgId(smsInfo.getMsgid());
		detail.setLocalMsgId(localMsgId);
		detail.setSendDate(new Date());
		detail.setSendSuccessFlag("0");
		detail.setUserDate(ConUtils.formatDate(new Date(), "yyyy-MM-dd"));
		detail.setOperators(operators);
		detail.setExtParm1(smsInfo.getExtParm1());
		detail.setExtParm2(smsInfo.getExtParm2());
		detail.setExtParm3(smsInfo.getExtParm3());
		detail.setExtParm4(smsInfo.getExtParm4());
		return detail;
	}
	
	private void sendUnicomResultToFile(Channel channel,SmsInfo smsInfo,String phone,String msgId){
		StringBuffer smsFileCont = new StringBuffer();
		User user = smsInfo.getOuser();
		String msg = smsInfo.getMsg();
		if("1".equals(user.getSignatureType())){
			//服务端加
			msg = msg + (user.getUnicomSignature()==null?"":user.getUnicomSignature());
		}
		if(StringUtils.isBlank(channel.getSignature())){
			smsInfo.setResult(msg);
		}else{
			smsInfo.setResult(msg+channel.getSignature());
		}
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append(phone).append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("1").append("\n");
		smsFileCont.append(channel.getAccessNumber()+
				(smsInfo.getOuser().getExpaCode()==null?"":smsInfo.getOuser().getExpaCode())+smsInfo.getExt()).append("\n");
		smsFileCont.append(channel.getServiceCode()==null?"":channel.getServiceCode()).append("\n");
		smsFileCont.append("1").append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("15").append("\n");
		smsFileCont.append(msgId).append("\n");
		smsFileCont.append(msg.getBytes().length).append("\n");
		try {
			smsFileCont.append(new String(msg.getBytes("UTF-8")));
			//smsFileCont.append(smsInfo.getMsg());
			FileUtils.writeStringToFile(new File(channel.getMtDir()+phone+msgId+ConUtils.formatseq()), smsFileCont.toString(),"GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void sendTelecomResultToFile(Channel channel,SmsInfo smsInfo,String phone,String msgId){
		StringBuffer smsFileCont = new StringBuffer();
		User user = smsInfo.getOuser();
		String msg = smsInfo.getMsg();
		if("1".equals(user.getSignatureType())){
			//服务端加
			msg = msg + (user.getTelecomSignature()==null?"":user.getTelecomSignature());
		}
		if(StringUtils.isBlank(channel.getSignature())){
			smsInfo.setResult(msg);
		}else{
			smsInfo.setResult(msg+channel.getSignature());
		}
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append(phone).append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("1").append("\n");
		smsFileCont.append(channel.getAccessNumber()+
				(smsInfo.getOuser().getExpaCode()==null?"":smsInfo.getOuser().getExpaCode())+smsInfo.getExt()).append("\n");
		smsFileCont.append(channel.getServiceCode()==null?"":channel.getServiceCode()).append("\n");
		smsFileCont.append("1").append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("15").append("\n");
		smsFileCont.append(msgId).append("\n");
		smsFileCont.append(msg.getBytes().length).append("\n");
		try {
			smsFileCont.append(new String(msg.getBytes("UTF-8")));
			//smsFileCont.append(smsInfo.getMsg());
			FileUtils.writeStringToFile(new File(channel.getMtDir()+phone+msgId+ConUtils.formatseq()), smsFileCont.toString(),"GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void sendMobileResultToFile(Channel channel,SmsInfo smsInfo,String phone,String msgId){
		StringBuffer smsFileCont = new StringBuffer();
		User user = smsInfo.getOuser();
		String msg = smsInfo.getMsg();
		if("1".equals(user.getSignatureType())){
			//服务端加
			msg = msg + (user.getMobileSignature()==null?"":user.getMobileSignature());
		}
		if(StringUtils.isBlank(channel.getSignature())){
			smsInfo.setResult(msg);
		}else{
			smsInfo.setResult(msg+channel.getSignature());
		}
		smsFileCont.append("\n");
		smsFileCont.append("09").append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append(channel.getAccessNumber()+
				(smsInfo.getOuser().getExpaCode()==null?"":smsInfo.getOuser().getExpaCode())+smsInfo.getExt()).append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("0").append("\n");
		smsFileCont.append("1").append("\n");
		smsFileCont.append(phone).append("\n");
		smsFileCont.append(channel.getServiceCode()==null?"":channel.getServiceCode()).append("\n");
		smsFileCont.append("1").append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append("\n");
		smsFileCont.append(channel.getBaseAmount()).append("\n");
		smsFileCont.append(msgId).append("\n");
		smsFileCont.append(msg.getBytes().length).append("\n");
		try {
			smsFileCont.append(new String(msg.getBytes("UTF-8")));
			//smsFileCont.append(smsInfo.getMsg());
			File file = new File(channel.getMtDir());
			File romFile = file.listFiles()[(int)(Math.random()*file.listFiles().length)];
			if(romFile.isDirectory()){
				String mtDir = romFile.getPath()+File.separator;
				FileUtils.writeStringToFile(new File(mtDir+phone+msgId+ConUtils.formatseq()), smsFileCont.toString(),"GBK");
			}else{
				logger.info("mt path is not Dir:"+phone+"\t"+msgId+"\t"+channel.getAccessNumber()+"\t"+user.getLoginName()+"\t"+msg);
			}
		} catch (Exception e) {
			logger.info("write mt file exc:"+phone+"\t"+msgId+"\t"+channel.getAccessNumber()+"\t"+user.getLoginName()+"\t"+msg);
			e.printStackTrace();
		}
	}
	
	private List<Channel> getChannelList(List userChannelList){
		List<Channel> list = new ArrayList<Channel>();
		if(userChannelList!=null && userChannelList.size()>0){
			for(int i=0;i<userChannelList.size();i++){
				Object[] obj = (Object[]) userChannelList.get(i);
				Channel channel = (Channel) obj[0];
				Long weight = (Long) obj[1];
				channel.setWeight(weight);
				list.add(channel);
			}
		}
		return list;
	}
}
